#include <iostream>
#include <cerrno>
#include <cstring>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

#include "comm.hpp"

int main()
{
    //1、创建管道文件
    umask(0);
    int n = mkfifo(fifoname.c_str(),mode);
    if(n != 0)
    {
        std::cout << errno << ":" << strerror(errno) << std::endl;
        return -1;
    }

    std::cout << "管道创建完成" << std::endl;

    //2、服务端开启管道文件
    int r_fd = open(fifoname.c_str(),O_RDONLY);
    if(r_fd < 0)
    {
        std::cout << errno << ":" << strerror(errno) << std::endl;
        return -2;
    }
    std::cout << "管道文件已经成功开启，等待通信" << std::endl;
    
    //3、正常进行通信：
    char buffer[NUM];
    while(true)
    {
        buffer[0] = '\0';
        ssize_t n = read(r_fd,buffer,sizeof(buffer));
        //系统调用都不去管C语言字符串的规定
        //std::cout << n << std::endl;
        if(n > 0)
        {
            buffer[n] = 0;
            std::cout << "clien:" << buffer << std::endl;
        }
        else if(n == 0)
        {
            std::cout << "client quit, me quit too!" << std::endl;
            break;
        }
        else 
        {
            std::cout << errno << ":" << strerror(errno) << std::endl;
            break;
        }
    }

    // 关闭
    close(r_fd);
    unlink(fifoname.c_str());

    return 0;
}